package whu.iss.system.db;

import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import whu.iss.mapper.EssayMapper;
import whu.iss.mapper.UserMapper;

public class DBUtils {
	
	private static SqlSessionFactory sqlSessionFactory;
	private static final ThreadLocal<SqlSession>  threadLocal=new ThreadLocal<>();
	
	private DBUtils() {}
	
    private static SqlSession getSqlSession () throws Exception
    {
		String resource = "SqlMapConfig.xml";
		// 得到配置文件流
		InputStream inputStream;
		inputStream = Resources.getResourceAsStream(resource);
		// 创建会话工厂，传入mybatis的配置文件信息
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
    	SqlSession sqlSession = threadLocal.get(); 
    	if(sqlSession==null)
    	{
    		//创建Connection
    		sqlSession=sqlSessionFactory.openSession();
    		//将连接对象与当前线程进行绑定
    		threadLocal.set(sqlSession);
    	}
		return sqlSession;
    } 
    
    public static UserMapper getUserMapper() throws Exception
    {
    	//创建UserMapper对象，mybatis自动生成mapper代理对象
		UserMapper userMapper = DBUtils.getSqlSession().getMapper(UserMapper.class);
		return userMapper;	
    }
    
    public static EssayMapper getEssayMapper() throws Exception
    {
    	//创建UserMapper对象，mybatis自动生成mapper代理对象
		EssayMapper essayMapper = DBUtils.getSqlSession().getMapper(EssayMapper.class);
		return essayMapper;	
    }
    
    public static void commit()throws Exception
    {
    	DBUtils.getSqlSession().commit();
    }
    
    public static void rollback()
    {
    	try 
    	{
			DBUtils.getSqlSession().rollback();
		} 
    	catch (Exception e) 
    	{
    		try
    		{
    			DBUtils.getSqlSession().rollback();
    		}
    		catch(Exception ex1)
    		{
    			ex1.printStackTrace();
    		}
			e.printStackTrace();
		}
    }
    
    public static void close() throws Exception
    {
    	try
    	{
    		//获取当前线程绑定的连接对象
    		SqlSession sqlSession=threadLocal.get();
    		if(sqlSession!=null)  //规避了空指针
    		{
    			System.out.println("------ Close SqlSession ---------------------------");
    			//解除绑定
    			threadLocal.set(null);
    			
    			sqlSession.close();
    		}
    	}
    	catch(Exception ex)
    	{
    		ex.printStackTrace();
    	}
    }
}
